package com.polaris.live.popup

import android.annotation.SuppressLint
import android.content.Context
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.StringUtils
import com.bumptech.glide.Glide
import com.lxj.xpopup.core.BottomPopupView
import com.polaris.live.R
import com.polaris.live.R.layout
import com.polaris.live.adapter.RoomUserAdapter
import com.polaris.live.common.R.color.*
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.ext.formatNumberWithK
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.network.request
import com.polaris.live.constant.LiveConst
import com.polaris.live.databinding.PopupRoomUserBinding
import com.polaris.live.im.sfs.bean.live.ext.UserBasicVo
import com.polaris.live.net.liveService
import com.polaris.live.translation.R.*
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.widget.avatar.FrameImageUtils

/**
 * 派对在线用户列表
 *
 * @author Created by 半仙 on 2024/9/23/023 16:15
 */
class RoomUserOnLinePopup(
    context: Context,
    private val mViewModel: BaseViewModel,
    private val mLiveId: Long,
    private val mHomeOwner: Long,
    private val mLiveType: Int,
    private val mAdministrators: List<Long>? = null,
    private val mOnHeadClickListener: ((otherId: Long) -> Unit)? = null,
    private val mOnSendGiftSomeOneCallback: ((base: UserBasicVo?) -> Unit)? = null,
) : BottomPopupView(context) {

    private lateinit var mBinding: PopupRoomUserBinding

    private val mAdapter by lazy { RoomUserAdapter(mHomeOwner, mAdministrators) }

    override fun getImplLayoutId() = layout.popup_room_user

    private var mPageNumber = 0

    private var mPageSize = 20

    @SuppressLint("SetTextI18n")
    override fun onCreate() {
        super.onCreate()
        mBinding = PopupRoomUserBinding.bind(popupImplView)

        mBinding.recycler.apply {
            recycler.adapter = mAdapter
            recycler.layoutManager = LinearLayoutManager(context)
            setEnableLoadMore(false)
            setOnRefreshListener {
                mPageNumber = 0
                requestData()
                mBinding.recycler.setEnableLoadMore(false)
            }
            setOnLoadMoreListener {
                mPageNumber += 1
                requestData()
                mBinding.recycler.setEnableRefresh(false)
            }
        }
        initListener()
        mBinding.recycler.autoRefresh()
    }

    private fun requestData() {
        mViewModel.request({ liveService.getRoomUser(mLiveId, mPageNumber, mPageSize) }, {
            mBinding.recycler.finishRefresh()
            mBinding.recycler.finishLoadMore()
            mBinding.recycler.setEnableLoadMore(true)
            mBinding.recycler.setEnableRefresh(true)
            mBinding.apply {
                val self = it.userSelf.base
                avFv.setFrameImage(FrameImageUtils.urlToFrameImageBean(self.avatarFrame))
                itemAvatar.setImageUrl(self.avatar, self.userId)

                itemName.text = self.nickname
                itemName.setNicknameColor(self.nicknameColor, color_202028)
                country.setCountry(self.country)
                ageSex.setSexAndAge(self.sex, self.birthday)
                vipView.setVipLevel(self.vipLevel)
                mBinding.level1.setRichsLevel(self.richs)
                mBinding.level2.setCharmsLevel(self.charms)
                tvCoin.text = it.userSelf.coin.formatNumberWithK()

                llFlag.setLabel(self.label)

                tvTitle.text =
                    "${StringUtils.getString(string.online_audience)}(${it.online}/${it.count})"
                if (mPageNumber == 0) {
                    mAdapter.setList(it.rank)
                } else {
                    mAdapter.addData(it.rank)
                }
                if (mHomeOwner == UserManager.getUserId()) {
                    ivUserIdentity.setImageResource(R.drawable.ic_rank_room)
                } else {
                    ivUserIdentity.setImageResource(R.drawable.ic_rank_indentity_audience)
                    if (mAdministrators?.isNotEmpty() == true && self.userId in mAdministrators) {
                        ivUserIdentity.setImageResource(R.drawable.ic_rank_indentity_administrator)
                    }
                }
                it.userSelf.background?.let {
                    Glide.with(bgImg)
                        .load(ImageUtils.imgPath(it))
                        .into(bgImg)
                    tvCoin.setTextColor(ColorUtils.getColor(R.color.white))
                }
                if (mAdapter.data.isEmpty()) {
                    mBinding.recycler.visibility = View.GONE
                    mBinding.llNotHava.visibility = View.VISIBLE
                } else {
                    mBinding.recycler.visibility = View.VISIBLE
                    mBinding.llNotHava.visibility = View.GONE
                }
            }
        }, {
            if (mAdapter.data.isEmpty()) {
                mBinding.recycler.visibility = View.GONE
                mBinding.llNotHava.visibility = View.VISIBLE
            } else {
                mBinding.recycler.visibility = View.VISIBLE
                mBinding.llNotHava.visibility = View.GONE
            }
        })
    }

    private fun initListener() {
        mBinding.consEnd.setOnSingleClickListener {
            if (mLiveType != LiveConst.Type.PARTY_LIVE && mLiveType != LiveConst.Type.PARTY_GAME_LIVE) {
                return@setOnSingleClickListener
            }
            mOnSendGiftSomeOneCallback?.invoke(null)
            dismiss()
        }
        mAdapter.setOnItemChildClickListener { _, view, position ->
            val item = mAdapter.getItem(position)
            when (view.id) {
                R.id.cons_end -> {
                    mOnSendGiftSomeOneCallback?.invoke(item.base)
                    dismiss()
                }

                R.id.item_avatar -> {
                    mOnHeadClickListener?.invoke(item.base.userId)
                    dismiss()
                }
            }
        }
    }
}